﻿using System.IO;
using System.Modules.ExceptionHanlding;
using System.Text;
using System.Xml.Serialization;

namespace System.Modules.Extensions
{
    /// <summary>
    /// Generics Extensions
    /// </summary>
    public static class GenericsExtensions
    {
        #region SerializeAsXml
        /// <summary>
        /// Use this method to Serialize a Generic Type to XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns>string</returns>
        public static string SerializeAsXml<T>(this T data)
        {
            var serializedXml = string.Empty;
            try
            {
                using (var stream = new MemoryStream())
                {
                    var serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(stream, data);
                    stream.Position = 0;
                    var bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, bytes.Length);
                    serializedXml = Encoding.UTF8.GetString(bytes);
                }
            }
            catch (Exception exception)
            {
                exception.Handle();
            }
            return serializedXml;
        } 
        #endregion

        #region DeserializeFromXml
        /// <summary>
        /// De-Serialize a XML to an Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns>T</returns>
        public static T DeserializeFromXml<T>(this string data)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                using (var reader = new StringReader(data))
                {
                    return (T)serializer.Deserialize(reader);
                }
            }
            catch (Exception exception)
            {
                exception.Handle();
                return default(T);
            }
        }
        #endregion
    }
}
